package com.ysh.dao.impl;

import com.ysh.dao.UserDao;
import com.ysh.domain.Student;
import com.ysh.domain.User;
import com.ysh.utils.JDBCUtils;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/*
    dao 持久层实现类

 */
public class UserDaoImpl implements UserDao {
    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;
    private String sql = null;

    /*
        添加用户信息
     */
    @Override
    public int addUser(User user) {
        // 定义返回值
        int result = 0;
        try {
            // 获取连接
            conn = JDBCUtils.getConnection();
            // 创建SQL语句
            sql = "insert into user values(?,?,?,?,?)";
            // 预编译，获取操作对象
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            pstmt.setString(1, user.getId());
            pstmt.setString(2, user.getName());
            pstmt.setInt(3, user.getAge());
            pstmt.setString(4, user.getSex());
            pstmt.setDouble(5, user.getMoney());
            // 4. 执行sql语句，获取结果集
            System.out.println(sql);
            result = pstmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.close(conn, pstmt);
        }
        // 返回结果
        return result;
    }

    /*
        查询用户信息
     */
    @Override
    public List<User> findUser() {
        User user = null;
        List<User> list = new ArrayList<>();
        try {
            // 获取连接
            conn = JDBCUtils.getConnection();
            // 创建SQL语句
            sql = "select * from user";
            // 预编译，获取操作对象
            pstmt = conn.prepareStatement(sql);
            // 4. 执行sql语句，获取结果集
            rs = pstmt.executeQuery();
            // 获取结果集
            while(rs.next()){
                user = new User(
                        rs.getString("id"),
                        rs.getString("name"),
                        rs.getInt("age"),
                        rs.getString("sex"),
                        rs.getDouble("money")
                );
                list.add(user);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.close(conn, pstmt,rs);
        }
        // 返回集合
        return list;
    }

}
